/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.app.service.index.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.buyer.CereBuyerSearchDAO;
import com.shop.cereshop.app.dao.location.CityDAO;
import com.shop.cereshop.app.dao.product.CereSkuMemberRealInfoDAO;
import com.shop.cereshop.app.dao.shop.CereBusinessTimeDAO;
import com.shop.cereshop.app.dao.shop.CerePlatformShopDAO;
import com.shop.cereshop.app.page.index.Index;
import com.shop.cereshop.app.page.index.Product;
import com.shop.cereshop.app.page.index.ProductClassify;
import com.shop.cereshop.app.page.index.RecommendShop;
import com.shop.cereshop.app.param.index.IndexParam;
import com.shop.cereshop.app.param.index.SearchParam;
import com.shop.cereshop.app.param.index.SearchParamUpdate;
import com.shop.cereshop.app.param.product.SearchHistoryDTO;
import com.shop.cereshop.app.service.buyer.CereBuyerSearchService;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.app.service.index.IndexService;
import com.shop.cereshop.app.service.product.CereProductClassifyService;
import com.shop.cereshop.app.service.product.CereShopProductService;
import com.shop.cereshop.app.service.shop.CerePlatformShopService;
import com.shop.cereshop.commons.cache.product.ProductBo;
import com.shop.cereshop.commons.domain.buyer.CereBuyerSearch;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.calculate.Calculate;
import com.shop.cereshop.commons.domain.canvas.CerePlatformCanvas;
import com.shop.cereshop.commons.domain.city.CereCityDetail;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.shop.CereBusinessTime;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    CereBusinessTimeDAO cereBusinessTimeDAO;

    @Autowired
    private CerePlatformShopService cerePlatformShopservice;

    @Autowired
    private CereProductClassifyService cereProductClassifyService;

    @Autowired
    private CereBuyerSearchService cereBuyerSearchService;

    @Autowired
    private CereShopProductService cereShopProductService;

    @Autowired
    private CereBuyerUserService cereBuyerUserService;

    @Autowired
    private CereSkuMemberRealInfoDAO cereSkuMemberRealInfoDAO;

    @Autowired
    private CityDAO cityDAO;

    @Autowired
    private CerePlatformShopDAO cerePlatformShopDAO;

    @Autowired
    CereBuyerSearchDAO cereBuyerSearchDAO;


    @Resource
    private RedisTemplate redisTemplate;


    @Value("${querySkuRealInfo}")
    private boolean querySkuRealInfo;

    @Override
    public Index index(IndexParam param, CereBuyerUser user) throws CoBusinessException {
        Index index = new Index();
        if (user != null) {
            //用户登录过
        } else {
            //第一次进来
        }
        //查询所有一级类目
        List<ProductClassify> classifies = cereProductClassifyService.findAll();
        //查询每周排名前十的好店推荐数据
        List<RecommendShop> shops = cerePlatformShopservice.findRecommendShop();
        if (!EmptyUtils.isEmpty(shops)) {
            shops.stream()
                    //查询该店销量最高商品数据
                    .peek(shop -> shop = cerePlatformShopservice.findVolumeProductByShopId(shop.getShopId()));
        }
        //查询好物推荐数据(销量前10商品数据)
        List<RecommendShop> products = cerePlatformShopservice.findRecommendProducts();
        if (!EmptyUtils.isEmpty(products)) {
            products.forEach(product -> {
                //设置付款人数
                product.setUsers(cerePlatformShopservice.findPayUsers(product.getProductId()));
                //设置活动信息
                ProductBo productBo = cereShopProductService.fetchProductCache(product.getShopId(), product.getProductId(), product.getSkuId(), user, false);
                if (productBo != null) {
                    product.setActivityType(productBo.getActivityType());
                    product.setOriginalPrice(productBo.getOriginalPrice());
                    product.setPrice(productBo.getPrice());
                    product.setTotal(productBo.getTotal());
                }
            });
        }
        index.setClassifies(classifies);
        index.setShops(shops);
        index.setProducts(products);
        return index;
    }

    @Override
    public List<CereBuyerSearch> getHistory(CereBuyerUser user) throws CoBusinessException {
        if (user != null) {
            return cereBuyerSearchService.getHistory(user.getBuyerUserId());
        }
        return null;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public Page getSearchProducts(SearchParam param, CereBuyerUser user) throws CoBusinessException {
        //过滤表情包参数
        param.setSearch(EmptyUtils.filterEmoji(param.getSearch()));
        if (!EmptyUtils.isEmpty(param.getSearch()) && user != null && param.getSearchType()!=null) {
            //查询当前搜索记录是否存在
            CereBuyerSearch cereBuyerSearch = cereBuyerSearchService.findBySearch(param.getSearch(), user.getBuyerUserId(), param.getSearchType());
            if (cereBuyerSearch == null) {
                //如果没有,新增搜索记录
                cereBuyerSearch = new CereBuyerSearch();
                cereBuyerSearch.setBuyerUserId(user.getBuyerUserId());
                cereBuyerSearch.setSearch(param.getSearch());
                cereBuyerSearch.setSearchType(param.getSearchType());
                cereBuyerSearchService.insert(cereBuyerSearch);
            }
        }
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Product> list = new ArrayList<>();
        if (querySkuRealInfo) {
            if (user != null && user.getMemberLevelId() > 0) {
                param.setMemberLevelId(user.getMemberLevelId());
            }
            list = cereSkuMemberRealInfoDAO.getSearchProducts(param);
        } else {
            list = cereShopProductService.getSearchProducts(param);
            if (!EmptyUtils.isEmpty(list)) {
                list.forEach(a -> {
                    //查询付款人数
                    a.setUsers(cerePlatformShopservice.findPayUsers(a.getProductId()));
                    //设置活动相关信息
                    ProductBo productBo = cereShopProductService.fetchProductCache(a.getShopId(), a.getProductId(), a.getSkuId(), user, false);
                    if (productBo != null) {
                        a.setActivityType(productBo.getActivityType());
                        a.setOriginalPrice(productBo.getOriginalPrice());
                        a.setPrice(productBo.getPrice());
                    }
                });
                if (param.getType() != null) {
                    if (param.getType() == 1) {
                        list = list.stream().sorted(Comparator.comparing(Product::getPrice)).collect(Collectors.toList());
                    } else if (param.getType() == 2) {
                        list = list.stream().sorted(Comparator.comparing(Product::getPrice).reversed()).collect(Collectors.toList());
                    }
                }
            }
        }

        PageInfo<Product> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public void deleteSearch(SearchParam param) throws CoBusinessException {
        cereBuyerSearchService.delete(param.getSearchId());
    }

    @Override
    public CerePlatformCanvas getCanvas(CerePlatformCanvas canvas) throws CoBusinessException {
        return cereBuyerUserService.getCanvas(canvas);
    }

    @Override
    public Page<CereBuyerSearch> getHistoryByPage(CereBuyerUser user, SearchHistoryDTO param) throws CoBusinessException {
        // 1. 处理分页参数默认值（防止 null）
        int pageNum = param.getPage() == null ? 1 : param.getPage();
        int pageSize = param.getPageSize() == null ? 10 : param.getPageSize();

        // 2. 未登录用户：返回空分页（total=0，list=[]）
        if (user == null) {
            return null; // 参数：当前页、每页条数、总条数
        }

        // 3. 登录用户：使用 PageHelper 分页查询
        PageHelper.startPage(pageNum, pageSize);  // 启动分页插件，拦截后续查询
      List<CereBuyerSearch> searchList= cereBuyerSearchDAO.getHistoryByPage(user.getBuyerUserId(),param.getType());  // DAO 查询（自动分页）

        // 4. 直接返回 Page 对象（已包含分页信息：list、total、pages 等）
        PageInfo<CereBuyerSearch> pageInfo = new PageInfo<>(searchList);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }


    @Override
    public Page getSearchProductsTitle(SearchParamUpdate param, CereBuyerUser user) throws CoBusinessException {
        // 过滤表情包参数
        param.setSearch(EmptyUtils.filterEmoji(param.getSearch()));
        if (!EmptyUtils.isEmpty(param.getSearch()) && user != null && param.getSearchType()!=null) {
            // 查询当前搜索记录是否存在
            CereBuyerSearch cereBuyerSearch = cereBuyerSearchService.findBySearch(param.getSearch(), user.getBuyerUserId(), param.getSearchType());
            if (cereBuyerSearch == null) {
                // 如果没有,新增搜索记录
                cereBuyerSearch = new CereBuyerSearch();
                cereBuyerSearch.setBuyerUserId(user.getBuyerUserId());
                cereBuyerSearch.setSearch(param.getSearch());
                cereBuyerSearch.setSearchType(param.getSearchType());
                cereBuyerSearch.setSearchType(1);
                cereBuyerSearchService.insert(cereBuyerSearch);

            }
            System.out.println(cereBuyerSearch);
        }

        if (param.getPage()==null||param.getPageSize()!=null){
            param.setPage(1);
            param.setPageSize(10);
        }

        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Product> list = new ArrayList<>();

        // 查询商品相关商品信息
        list = cereShopProductService.getSearchProductsTitle(param);


//        Map<Long,Map<String,Object>> shopIdList = cerePlatformShopDAO.getInstanceToProduct(
//                param.getCityCode(),    // 城市编码（缩小查询范围）
//                param.getLocation()  // 用户经纬度
//        );
//
//        //            取出计算用户到商家之间的距离是多少
//        for (Product product : list) {
//            Double distance=null;
//            if ( shopIdList.get(product.getShopId())!=null) {
//                distance = (Double) shopIdList.get(product.getShopId()).get("distance");
//            }
//            product.setUserAndShopDistance(distance);
//        }

        if (!EmptyUtils.isEmpty(list)) {

            list = list.stream().map(a -> {
                        // 获取店铺的营业时间
                        QueryWrapper<CereBusinessTime> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("shop_id", a.getShopId());
                        List<CereBusinessTime> bussinessTimes = cereBusinessTimeDAO.selectList(queryWrapper);
                        a.setWeek(bussinessTimes);
                        Object productSignal = redisTemplate.opsForHash().get("product", String.valueOf(a.getProductId()));

                        //Calculate
                        if (null != productSignal) {
                            Calculate calculate = JSONUtil.toBean(JSONObject.toJSONString(productSignal), Calculate.class);
                            if (calculate != null) {
                                a.setProductLabels(calculate);
                            }
                        }

// 判断 bussinessTimes 是否为空
                        boolean isAllDay = bussinessTimes.isEmpty() ? false : bussinessTimes.stream()
                                .allMatch(bt -> {
                                    if (bt.getStartTime() != null && bt.getEndTime() != null) {
                                        String startTimeStr = bt.getStartTime();
                                        String endTimeStr = bt.getEndTime();
                                        return "00:00:00".equals(startTimeStr) && "23:59:59".equals(endTimeStr);
                                    }
                                    return false;
                                });

                        a.setAllDayToUse(isAllDay ? 1 : 0); // 设置是否全天的标志
                        a.setWeek(bussinessTimes);

//                         判断商品类型
//                if (a.getClassifyId2() != null) {
//                    if (a.getClassifyId2() == 908) {
//                        a.setStatus(ShopTypeEnum.TONGCHENGFUWU.getCode()); // 同城服务
//                    } else if (a.getClassifyId2() == 910) {
//                        a.setStatus(ShopTypeEnum.TONGCHENGPEISONG.getCode()); // 线上商城
//                    } else if (a.getClassifyId2() == 929) {
//                        a.setStatus(ShopTypeEnum.XIANSHANGSHANGCHENG.getCode()); // 同城配送
//                    }
//                }
                return a;
            }).collect(Collectors.toList()); // 收集结果



            // 根据是否全天筛选
            if (param.getAllDays() != null) {
                if (param.getAllDays() == 1) {
                    list = list.stream().filter(a -> a.getAllDayToUse() == 1).collect(Collectors.toList());
                } else {
                    list = list.stream().filter(a -> a.getAllDayToUse() != 1).collect(Collectors.toList());
                }
            }
        }

//        对用用户输入的距离进行筛选
        if (param.getDistance() != null) {
           list= list.stream()
                    .filter(product -> product.getUserAndShopDistance() <= param.getDistance())
                    .collect(Collectors.toList());
        }
        PageInfo<Product> pageInfo = new PageInfo<>(list);
        Page page = new Page(pageInfo.getList(), pageInfo.getTotal());
        return page;
    }


    @Override
    public String getCityName(String cityCode) throws CoBusinessException {
        // 使用 QueryWrapper 构造查询条件
        QueryWrapper<CereCityDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("adcode", cityCode);
        queryWrapper.select("name"); // 只查询 name 字段

        CereCityDetail cityDetail = cityDAO.selectOne(queryWrapper);
        return cityDetail != null ? cityDetail.getName() : null;
    }


}

